package cn.cheneyjoo.config;


import cn.cheneyjoo.io.Resources;
import cn.cheneyjoo.model.Configuration;
import cn.cheneyjoo.model.MappedStatement;
import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 将二进制流转换为Configuration对象
     * @param inputStream 解析配置文件的二进制流对象
     * @return SQL Configuration对象
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> nodes = rootElement.selectNodes("//property");
        Properties properties=new Properties();
        for (Element node : nodes) {
            String name = node.attributeValue("name");
            String value = node.attributeValue("value");
            properties.setProperty(name,value);
        }
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        dataSource.setUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        // 获取Mapper标签的值，解析Mapper.xml的内容
        List<Element> mapperNodes = rootElement.selectNodes("//mapper");
        for (Element mapperNode : mapperNodes) {
            String resource = mapperNode.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);

            XMLMapperBuilder xmlMapperBuilder=new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parseMapper(resourceAsStream);
        }
        return configuration;
    }
}
